package com.example.user.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.albumtype.mapper.AlbumtypeMapper;
import com.example.albumtype.service.IAlbumtypeService;
import com.example.photomessage.entity.PhotoMessage;
import com.example.photomessage.mapper.PhotoMapper;
import com.example.user.bean.UserPhotoMsg;
import com.example.user.entity.User;
import com.example.user.service.IUserService;
import com.example.user.userUtil.ExcelUserModel;
import com.example.user.userUtil.UserMessage;
import com.example.util.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;


/**
 *@author 贾明祯
 *@ClassName UserController
 *@Date 2020/8/13 13:38
 */
@Controller
@RequestMapping("/user")
public class UserController {
    private String PREFIX = "/user/";
    @Autowired
    private IUserService userService;
    @Autowired
    private PhoneMessage phoneMessage;
    @Autowired
    private PhotoMapper photoMapper;



    /**
     * @Author: 贾明祯
     * @Date: 2020/8/17 11:08
     * @Introduce: 注册用户
     */
    @RequestMapping("/registerUser")
    @ResponseBody
    public Result registerUser(User user){
        return userService.registerUser(user);
    }

    @RequestMapping("/userTable")
    public String userTable(){
        return PREFIX+"/table";
    }

    /**
     * @Author: 贾明祯
     * @Date: 2020/8/17 15:33
     * @Introduce: 用户账号登录
     */
    @RequestMapping("/userLogin")
    @ResponseBody
    public Result userLogin(HttpServletRequest request,HttpServletResponse response,HttpSession session,String account,String password,String code) throws UnsupportedEncodingException {
        try{
            request.setCharacterEncoding("utf-8");
            String session_vcode=(String) request.getSession().getAttribute("text");    //从session中获取真正的验证码
            if(StringUtils.isEmpty(code)){
                return Result.error(500,"验证码错误");
            }else if(session_vcode.equals(code)){
                QueryWrapper<User> ew = new QueryWrapper<>();
                ew.eq("account",account);
                User user = userService.getOne(ew);
                System.out.println(user);
                if(user!=null){
                    password = PasswordUtil.getMD5Str(password,user.getSalt());
                }

                UsernamePasswordToken userToken =  new UsernamePasswordToken(account,password);
                Subject subject = SecurityUtils.getSubject();
                subject.login(userToken);
            }else{
                return Result.error(500,"验证码错误");
            }
        } catch (UnknownAccountException e) {
            return Result.error(500,"该账号不存在");
        } catch (IncorrectCredentialsException e) {
            return Result.error(500,"密码错误，请重试");
        } catch (LockedAccountException e) {
            return Result.error(500,"该账户已被锁定,请联系管理员");
        } catch (Exception e) {
            return Result.error(500,"登录失败");
        }
//        String token = JedisUtil.getString(account);
//        if(StringUtils.isNotEmpty(token)){
//
//        }else {
//            JedisUtil.setString(UUID.randomUUID().toString(),account);
//        }

        return Result.success(200,"登录成功");
    }
    /**
     * 退出登录返回登录页
     */
    @RequestMapping("/loginOut")
    public String loginOut(HttpServletRequest request, HttpServletResponse response) throws IOException {
        SecurityUtils.getSubject().logout();
        return "redirect:/testLogin";
    }
    /**
     * @Author: 贾明祯
     * @Date: 2020/8/21 8:48
     * @Introduce: 获取短信验证码
     */
    @RequestMapping("/phoneCode")
    @ResponseBody
    public Result phoneCode(String phone){
        String code = phoneMessage.getPhoneCode(phone);
        if(code!=null){
            JedisUtil.setString(phone,code);
            JedisUtil.setKeyTime(phone);
            return Result.success(200,"发送成功");
        }
        return Result.error(500,"发送失败");
    }

    /**
     * @Author: 贾明祯
     * @Date: 2020/8/21 9:05
     * @Introduce: 手机验证码登录
     */
    @RequestMapping("/phoneLogin")
    @ResponseBody
    public Result phoneLogin(String phone,String code){
        User user = userService.phoneLogin(phone);
        /**
         * 获取缓存中的验证码
         */
        String security = JedisUtil.getString(phone);
        if(user!=null){
            /**
             * 缓存中验证码是否为空
             */
            if(security!=null){
                /**
                 * 对比输入的验证码和缓存中的是否相等
                 */
                if(security.equals(code)){
                    /**
                     * 删除缓存中的验证码
                     */
                    JedisUtil.delKey(phone);
                    return Result.success(200,"登录成功");
                }
            }else {
                return Result.error(500,"验证码已失效");
            }
        }
        return Result.success(500,"登录失败");
    }

    /**
     * @Author: 贾明祯
     * @Date: 2020/8/17 15:11
     * @Introduce: 修改用户数据
     */
    @RequestMapping("/changeUser")
    @ResponseBody
    public Result changeUser(User user, HttpSession session){
        return userService.changeUser(user,session);
    }

    /**
     * @Author: 贾明祯
     * @Date: 2020/8/17 15:13
     * @Introduce: 修改密码
     */
    @RequestMapping("/changeUserPassword")
    @ResponseBody
    public Result changeUserPassword(String oldPassWord,String newPassword,HttpSession session){
        return userService.changeUserPassword(oldPassWord, newPassword, session);
    }
    @RequestMapping("/userMessageTable")
    @ResponseBody
    public PageResult userMessageTable(Integer page,Integer limit,User user,HttpSession session){
        return userService.listPage(page, limit, user);
    }

    /**
     * @Author: 贾明祯
     * @Date: 2020/8/21 17:03
     * @Introduce: 用户信息导出
     */
    @RequestMapping("/excl")
    public void excl(HttpServletResponse response) throws Exception {
        ArrayList<ExcelUserModel> data = new ArrayList<>();
        List<User> list = userService.selectList();
        String fileName = "用户信息";
        for(User user : list){
            ExcelUserModel excelUserModel = new ExcelUserModel();
            excelUserModel.setId(user.getId());
            excelUserModel.setNickName(user.getNickName());
            excelUserModel.setAccount(user.getAccount());
            excelUserModel.setEmail(user.getEmail());
            if(user.getSex()==1){
                excelUserModel.setSex("男");
            }else {
                excelUserModel.setSex("女");
            }
            excelUserModel.setName(user.getName());
            excelUserModel.setAge(user.getAge());
        }
        EasyExcelUtil.writeExcel(response,data,fileName,fileName,new ExcelUserModel());
    }
}
